import Vue from "vue";

import axios from 'axios'
// import {url} from "./config";
import { Message } from "element-ui";
import router from "@/router";
import store from "@/store";
import encryption from '@/utils/encryption'
import env from "@/utils/env"
//

class Interceptors {
  constructor() {
    this.instance = axios.create()
    this.initInterceptors()
  }

  getInterceptors() { // 为了获取初始化好的 axios`
    return this.instance
  }

  initInterceptors() {

    this.instance.interceptors.request.use((config) => {
      const constructorVue = new Vue({
        store
      })

      const accessToken = constructorVue.$store.state.user.TOKEN
      config.timeout = 10000;
      config.baseURL = env.BASE_URL;
      if (accessToken) {
        config.headers["access-token"] = accessToken;
      }

      if (config.data) {
        if(config.url == "/homework/zhty/stuHealth/importHealthTable"){
          return config;
        } else{
          config.data = { param: encryption(JSON.stringify(config.data)) }
        }
      }
      return config;
    }, (error) => {
      return Promise.reject(error)
    })
    this.instance.interceptors.response.use((response) => {
      const constructorVue = new Vue({
        router
      })
      if (response.data.code === 401) {
        constructorVue.$router.replace("/")
        Message.error("您的身份信息已过期，请重新登录");
        sessionStorage.removeItem("userInfo");
        sessionStorage.removeItem("token");
        store.commit("user/SET_TOKEN", "")
      }
      return Promise.resolve(response.data)
    }, (error) => {
      return Promise.reject(error)
    })
  }
}

export default new Interceptors().getInterceptors()
